import { ElMessageBox, ElNotification } from "element-plus";
import { defineStore } from "pinia";
import axios from "axios";
import { h } from "vue";
import dayjs from "dayjs";
import useCommonStore from "@/store/common.js";
import useJournalStore from "@/store/journal.js";
// import pinia from "@/store/index.js";

const useStore = defineStore({
  id: "seatStatus",
  state: () => ({
    currentSeat: {
      ip: "0.0.0.0",
      seatName: "",
    },
    // warning time
    lastWarningTime: -1,
    // seatStatusTMA
    seatStatus: [],
    seatStatusFull: null,
    seatStatusVersion: -1,
    seatStatusFreshness: -1,
    seatStatusAvailable: true,
    seatStatusReciveTime: new Date().getTime(),
    indicatorSettings: {
      showTags: true,
      graphicIndex: 0,
      fontSize: 12,
      showBorder: true,
      unhoveredOpcity: 0.7,
    },
    valueTarget: "current",
    messageDuration: 60 * 1000,
    lastSeenDaysRequirement: 29,
    lastSeenData: {},
    // seatStatusACC
    seatStatusACC: [],
    seatStatusACCFull: [],
    seatStatusACCVersion: -1,
    // seatStatusTWR
    seatStatusTWR: [],
    seatStatusTWRFull: [],
    seatStatusTWRVersion: -1,
    viewSelect: "TMA",
    historyView: {
      isLoading: false,
      queryConfig: {
        dateRange: [
          // dayjs().subtract(24, "hour").format("YYYY-MM-DD"),
          // dayjs().subtract(24, "hour").format("YYYY-MM-DD"),
          dayjs().format("YYYY-MM-DD"),
          dayjs().format("YYYY-MM-DD"),
        ],
        ignoreShort: true,
      },
      viewConfig: {
        showImage: true,
        showAllSeats: false,
        momentReversed: false,
        ignoreDirection: true,
        ignoreUser: true,
      },
      summaryConfig: {
        stepMinutes: 30,
        valueType: "weighted",
      },
      queryResult: [],
    },
    atis: [],
  }),
  getters: {
    isServiceAvailable() {
      return this.seatStatusAvailable;
    },
    isSeatAvailable() {
      // sipds or local ip address
      return (
        this.currentSeat.ip.includes("10.202.91.") ||
        this.currentSeat.ip.includes("127.0.0.1") ||
        this.currentSeat.ip.includes("172.22.215.100") ||
        this.currentSeat.ip.includes("192.168.")
      );
    },
    currentSeatData() {
      if (!this.currentSeat.seatName) return null;
      if (this.seatStatusFull.length == 0) return null;
      for (let i = 0; i < this.seatStatusFull.length; i++) {
        if (this.seatStatusFull[i].seatName == this.currentSeat.seatName)
          return this.seatStatusFull[i];
      }
      return null;
    },
    isPlanningExisted() {
      // judge if planning data is existed
      for (let i = 0; i < this.seatStatus.length; i++) {
        if (
          this.seatStatus[i].planningSectorCodes != null ||
          this.seatStatus[i].planningFrequency != null
        ) {
          return true;
        }
      }
      return false;
    },
  },
  actions: {
    requestData(force = false) {
      const commonStore = useCommonStore();
      // 时间差大于 threshold 则进行认为已过期，单位：秒
      const threshold = 180;
      // 时间差大于 warningThreshold 则进行弹出提醒，单位：秒
      const warningThreshold = 60 * 1000;
      this.getCurrentSeat();
      this.reloadSeatStatus();
      this.getSeatStatus()
        .then((vals) => {
          if (!commonStore.isReal) {
            // 演示模式，则设置 seatStatusVersion 为当前时间戳，单位：毫秒
            this.seatStatusVersion = new Date().getTime();
            this.seatStatusFreshness = 0;
          }
          let diff = dayjs().diff(this.seatStatusVersion, "second");
          if (diff < threshold) {
            console.log(
              "seatStatusVersionDiff",
              dayjs(this.seatStatusVersion).format("YYYY-MM-DD HH:mm:ss"),
              diff,
              this.currentSeat.ip
            );
            if (this.isSeatAvailable) {
              this.seekLastSeen(vals);
              this.inspectDifferences(vals);
              this.triggerTimer(vals);
            }
          } else {
            let time = new Date().getTime();
            if (time - this.lastWarningTime > warningThreshold) {
              this.lastWarningTime = time;
              ElNotification({
                title: "扇区信息已经过期",
                type: "error",
                position: "bottom-right",
              });
            }
          }
        })
        .catch((err) => {
          // ...
        });
    },
    getCurrentSeat() {
      //get information of current seat. (Ip address and seat name)
      return new Promise((resolve, reject) => {
        axios
          .get("api/get_seat_by_ip.php")
          .then((response) => {
            this.currentSeat.ip = response.data.ip;
            this.currentSeat.seatName = response.data.seat;
            resolve();
          })
          .catch((error) => {
            console.log(
              "An error occured while requesting 'api/get_seat_by_ip'",
              error
            );
            reject(error);
          });
      });
    },
    seekLastSeen({ oldRes, newRes }) {
      // 用于查询该人员最后一次值守该席位所有模块（以最早为准）的时间
      // if (oldRes.length == 0) return null;
      let result = new Array();
      let userCount = 0;
      let userChecked = 0;
      let existList = new Array();
      let seekList = new Array();
      this.lastSeenData = {};
      oldRes.forEach((seat) => {
        seat.users.forEach((user) => {
          existList.push(user.userName);
        });
      });
      let threshold = this.lastSeenDaysRequirement;
      newRes.forEach((seat, index_seats) => {
        this.lastSeenData[seat.seatName] = new Array();
        seat.users.forEach((user, index_users) => {
          if (!existList.includes(user.userName) && user.seatRoleId !== 3) {
            userCount++;
            seekList.push({ name: user.userName, codes: seat.sectorCodes });
            axios
              .post("api/seat_seeking_lastseen.php", {
                content: {
                  name: user.userName,
                  codes: seat.sectorCodes,
                },
              })
              .then((response) => {
                userChecked++;
                this.lastSeenData[seat.seatName].push(response.data);
                let diff = dayjs().diff(response.data.lastseen, "day");
                if (threshold < diff) {
                  result.push(
                    h(
                      "div",
                      {
                        style: {
                          borderTop: "1px dotted rgba(128,128,128,0.5)",
                          padding: "6px",
                        },
                      },
                      [
                        h(
                          "div",
                          { style: "font-weight:bold" },
                          `${user.userName} 已经 ${diff} 天未在 ${seat.seatName} 所包含的全部模块执勤`
                        ),
                        h(
                          "div",
                          {
                            style: {
                              // paddingBottom: "12px",
                              fontWeight: "normal",
                            },
                          },
                          response.data.details.map((sector) => {
                            let diff2 = dayjs().diff(sector.lastseen, "day");
                            return h(
                              "div",
                              {
                                style: {
                                  // color: "var(--el-color-info)",
                                  // threshold < diff2
                                  //   ? "var(--el-color-error)"
                                  //   : "var(--el-color-info)",
                                },
                              },
                              [
                                h(
                                  "span",
                                  { style: "font-weight:bold" },
                                  sector.code
                                ),
                                h(
                                  "span",
                                  { style: "padding-left:12px" },
                                  diff + "天前"
                                ),
                                h(
                                  "span",
                                  { style: "padding-left:12px" },
                                  sector.lastseen
                                ),
                              ]
                            );
                          })
                        ),
                      ]
                    )
                  );
                }
                if (userChecked == userCount && result.length > 0) {
                  ElMessageBox({
                    title: `席位熟练度提醒（${result.length}人）`,
                    message: h(
                      "div",
                      {
                        style: {
                          maxHeight: "450px",
                          overflow: "auto",
                        },
                      },
                      result
                    ),
                    draggable: true,
                    // customClass: "msgbox-rock-gradient",
                    // confirmButtonClass: "msgbox-main-btn",
                    confirmButtonText: "知道了",
                  });
                }
              })
              .catch((error) => console.log(error));
          }
        });
      });
    },
    inspectDifferences({ oldRes, newRes }) {
      // 用于检查最新的扇区信息和上一次的有无区别，如果有，则检索发生变化的席位并弹出提示
      let oldVal = JSON.parse(JSON.stringify(oldRes));
      let newVal = JSON.parse(JSON.stringify(newRes));
      let messages = new Array();
      // .sort((a, b) => a.seatName - b.seatName);
      if (oldVal.length == 0) {
        // console.log("ignored to inspect differences of seat status");
        return false;
      } else if (oldVal.length != newVal.length) {
        console.log("warning! different number of seats!");
        return false;
      } else {
        // compare each seat status
        for (let i = 0; i < oldVal.length; i++) {
          if (oldVal[i].borderOn) {
            for (let j = 0; j < newVal.length; j++) {
              if (oldVal[i].seatName == newVal[j].seatName) {
                if (
                  oldVal[i].frequency != newVal[j].frequency &&
                  newVal[j].sectorCodes.length > 0
                ) {
                  messages.push(
                    h(
                      "div",
                      null,
                      oldVal[i].seatName + "的频率变更为" + newVal[j].frequency
                    )
                  );
                }
                if (
                  oldVal[i].sectorCodes.length != 0 &&
                  newVal[j].sectorCodes.length != 0 &&
                  oldVal[i].sectorCodes.sort().toString() !=
                    newVal[j].sectorCodes.sort().toString()
                ) {
                  // sector changed
                  messages.push(
                    h(
                      "div",
                      null,
                      oldVal[i].seatName +
                        "的扇区变更为" +
                        newVal[j].sectorCodes.sort().join(", ")
                    )
                  );
                } else if (
                  oldVal[i].sectorCodes.length != 0 &&
                  newVal[j].sectorCodes.length == 0
                ) {
                  // seat close
                  messages.push(
                    h(
                      "div",
                      null,
                      oldVal[i].seatName +
                        "合扇了：" +
                        oldVal[i].sectorCodes.sort().join(", ") +
                        "已合并至其他席位"
                    )
                  );
                } else if (
                  oldVal[i].sectorCodes.length == 0 &&
                  newVal[j].sectorCodes.length != 0
                ) {
                  // seat open
                  messages.push(
                    h(
                      "div",
                      null,
                      oldVal[i].seatName +
                        "席位开扇了：" +
                        newVal[j].sectorCodes.sort().join(", ") +
                        "已划扇"
                    )
                  );
                }
              }
            }
          }
        }
        // return true;
      }
      if (messages.length > 0) {
        messages.push(
          h(
            "div",
            {
              style: {
                paddingTop: "4px",
                fontSize: "12px",
                opacity: "0.5",
              },
            },
            "@" + dayjs().format("HH:mm:ss")
          )
        );
        ElNotification({
          title: "扇区信息变更",
          message: h("div", null, messages),
          type: "warning",
          duration: this.messageDuration,
          position: "bottom-right",
        });
      }
    },
    getSeatStatus() {
      // 用于查询当前的席位信息
      // 如果和上一次获取的信息一致，则reject
      // 否则resolve(oldRes,newRes)
      // 其中oldRes是上一次更新的信息，newRes是本次更新的信息
      return new Promise((resolve, reject) => {
        axios
          .get("api/seat_status_get.php?seat=*")
          .then((response) => {
            if (!response.data.success) {
              reject(response.data);
            }
            this.seatStatusVersion = response.data.version;
            this.seatStatusAvailable = response.data.available;
            this.seatStatusFreshness = response.data.freshness;
            this.seatStatusReciveTime = new Date().getTime();
            let newResFull = response.data.content;
            let newRes = response.data.content.filter(
              (item) => item.seatType == "普通管制" || item.sectorYes
            );
            let oldRes = this.seatStatus;
            let newResJSON = JSON.stringify(newRes);
            let oldResJSON = JSON.stringify(oldRes);
            if (newResJSON == oldResJSON) {
              // no change
              reject("getSeatStatus: 扇区信息未发生变更");
            } else {
              let sectorCodeList = [];
              let sectorCodeCount = 0;
              for (let i = 0; i < newRes.length; i++) {
                sectorCodeCount += newRes[i].sectorCodes.length;
                sectorCodeList = [...sectorCodeList, ...newRes[i].sectorCodes];
              }
              if (sectorCodeList.length < 0) {
                sectorCodeList.length < 19;
                console.log(
                  "Disposed response (" + sectorCodeCount + "<19)!",
                  sectorCodeList.join(", ")
                );
                reject("Disposed response (" + sectorCodeCount + "<19)!");
              } else {
                // resolve olerRes and newRes
                resolve({ oldRes, newRes });
                // set new seatStatus
                this.seatStatus = newRes;
                this.seatStatusFull = newResFull;

                if (!this.isPlanningExisted) {
                  this.valueTarget = "current";
                }
                // this.$emit("updated", this.seatStatus);
              }
            }
          })
          .catch((error) => {
            console.error(
              "An error occured while requesting 'api/seat_status_get'",
              error
            );
            reject(error);
          });
      });
    },
    reloadSeatStatus(force = false) {
      return new Promise((resolve, reject) => {
        if (!this.isSeatAvailable) {
          // 若并非生产环境，停止自动访问agent_atcos_load，防止清空扇区信息
          reject("reloadSeatStatus: 非生产环境, 停止访问 api/agent_atcos_load");
        } else {
          axios
            .get("api/agent_atcos_load.php")
            .then((response) => {
              // console.log("reloadSeatStatus", response);
              resolve();
            })
            .catch((error) => {
              console.error("reloadSeatStatus", error);
              reject(error);
            });
        }
      });
    },
    triggerTimer({ oldRes, newRes }) {
      // @2025-06-16
      // 用于检测席位上是否新增了放单及以上资质的人员
      const journalStore = useJournalStore();
      // 本席位的名称
      let seatName = this.currentSeat.seatName;
      // console.log("triggerTimer", { seatName, journalStore });
      // 筛选更新前和更新后的席位
      let oldResFiltered = oldRes.filter((seat) => seat.seatName == seatName);
      let newResFiltered = newRes.filter((seat) => seat.seatName == seatName);
      // console.log("triggerTimer", { oldResFiltered, newResFiltered });
      if (oldResFiltered.length > 0 && newResFiltered.length > 0) {
        // 若更新前后的数据均包含当前席位
        let oldUsers = oldResFiltered[0].users.filter((u) => u.seatRoleId <= 2);
        let newUsers = newResFiltered[0].users.filter((u) => u.seatRoleId <= 2);
        // console.log("triggerTimer", { oldUsers, newUsers });
        if (oldUsers.length >= 2 && newUsers.length > oldUsers.length) {
          // 更新前的席位人员≤2，且更新后的席位人员多于更新前
          if (journalStore.timerStatus.timerID == 0) {
            // 如果不存在已有的计时器
            // 设置默认计时时间
            // journalStore.timerStatus.configDuration = 300000;
            journalStore.timerStatus.currentDuration = 300000;
          }
          // 弹出计时器窗口
          journalStore.timerStatus.showMainWindow = true;
          // 弹出提示信息
          ElNotification({
            title: seatName + " 人员变更",
            type: "success",
            message: h("div", null, [
              h("div", null, "检测到本席位放单人员增加了, 已打开计时器"),
              h(
                "div",
                {
                  style: {
                    paddingTop: "4px",
                    fontSize: "12px",
                    opacity: "0.5",
                  },
                },
                "@" + dayjs().format("HH:mm:ss")
              ),
            ]),
            position: "bottom-right",
            duration: 120000,
          });
          // 控制台打印信息
          // console.log("triggerTimer: 席位放单人员增加，弹出计时器", {
          //   seat: seatName,
          //   before: oldUsers.map((u) => u.userName),
          //   after: newUsers.map((u) => u.userName),
          // });
        } else if (
          newUsers.length <= 2 &&
          journalStore.timerStatus.timerID == 0 &&
          journalStore.timerStatus.showMainWindow == true
        ) {
          // 如果席位放单人员小于等于2
          // 如果不存在已有的计时器
          // 如果计时器窗口已打开
          // 自动关闭计时器
          journalStore.timerStatus.showMainWindow = false;
        }
      }
    },
  },
});

export default useStore;
